package dashboard;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ChangeSettingsServlet extends HttpServlet {


	private ChangeSettingsController CSC = new ChangeSettingsController();

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String[] allCourses = req.getParameterValues("courses");
		String firstName = req.getParameter("firstname");
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		String cpassword = req.getParameter("cpassword");
		String number = req.getParameter("number");
		String email = req.getParameter("email");
		String role = req.getParameter("role");
		int treshold = Integer.parseInt(req.getParameter("treshold"));

		HttpSession session = req.getSession();
		
		CSC.setUser((User) session.getAttribute("user"));
		
		boolean finished = true;
		
		
		if(password != null  || email != null)
			if(CSC.setInfo(password, cpassword, email, firstName, name, allCourses, number, role, treshold).size() != 0)
				finished = false;
		
		CSC.getUser().clearCourses();
		
		if (allCourses != null) 
		   {
		      for (int i = 0; i < allCourses.length; i++) 
		      {
		    		  CSC.getUser().addCourse( Long.parseLong(allCourses[i]));
		      }

		   }
		
		if(finished){
			CSC.saveUser();
			session.setAttribute("csUser", null);
			resp.sendRedirect("dashboard.jsp?CS=true");
			
			
		}
		else
		{
			session.setAttribute("errors", CSC.setInfo( password, cpassword, email, firstName, name, allCourses, number, role, treshold));
			session.setAttribute("csUser", CSC.getUser());
			resp.sendRedirect("changesettings.jsp" );
		}
	}
}